using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Data;
using System.IO;
using System.Web.Mail;

namespace Umbraco.Ecommerce
{
    /// <summary>
    /// Function library for the umbraco storeextension.
    /// Has methods to get information regarding the "product + ProductVariants" and methods to get data of
    /// the current users cart, adding/removing products of the cart.
    /// </summary>
    public class Library
    {
        private static string _ErrorMessage = "";


        /* 
         * This method is enabling debug information to be passed along 
         * doing them umbraco situps.. 
         */
        public static string ErrorMessage()
        {
            return _ErrorMessage;
        }


        /* The XML output of this method:
         * <product>
         *	<productVariant>
         *		<id>int32</id>
         *		<productId>string</productId>
         *		<name>string</name>
         *		<price>decimal</price>
         *		<displayPrice>currency string</displayPrice>
         *  </productVariant>
         *  <productVariant>
         *	   ...
         *  </productVariant>
         * </product>
         */

        public static XPathNodeIterator GetProductXML(int NodeId)
        {
            try
            {
                BusinessLogic.Product p = new BusinessLogic.Product(NodeId);
                DataTable dt = new DataTable("productVariant");
                dt.Columns.Add("id");
                dt.Columns.Add("productId");
                dt.Columns.Add("name");
                dt.Columns.Add("price");
                dt.Columns.Add("displayPrice");

                foreach (BusinessLogic.ProductVariant v in p.ProductVariants)
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = v.Id;
                    dr["productId"] = v.ProductId;
                    dr["name"] = v.Name;
                    dr["price"] = v.Price;
                    dr["displayPrice"] = v.Price.ToString("c", BusinessLogic.Store.NumberFormatInfo);
                    dt.Rows.Add(dr);
                }

                DataSet ds = new DataSet("product");
                ds.Tables.Add(dt);

                XmlDataDocument xdoc = new XmlDataDocument(ds);
                XPathNodeIterator xp = xdoc.CreateNavigator().Select(".");
                _ErrorMessage = "";
                return xp;
            }
            catch
            {
                _ErrorMessage = "No product with NodeId = " + NodeId;
                return null;
            }
        }


        public static Cart GetCart
        {
            get
            {
                if (System.Web.HttpContext.Current.Session["cart"] == null)
                {
                    System.Web.HttpContext.Current.Session["cart"] = new Cart();
                }
                return (Cart)System.Web.HttpContext.Current.Session["cart"];
            }
        }

        public static void AddProductToCart(string ProductId, int Quantity)
        {
            try
            {
                BusinessLogic.ProductVariant v = BusinessLogic.ProductVariant.ProductVariantFromProductId(ProductId);

                CartItem c = new CartItem();
                c.ProductId = v.ProductId;
                c.Price = v.Price;
                c.Quantity = Quantity;
                c.ProductName = v.FullName;
                c.Url = umbraco.library.NiceUrl(v.Product.NodeId);

                GetCart.AddItemToCart(c);
                _ErrorMessage = "";
            }
            catch (Exception ex)
            {
                _ErrorMessage = "Error adding ProductVariant with id:" + ProductId + ex.ToString();
            }
        }

        public static void RemoveProduct(string ProductId)
        {
            try
            {

                CartItem c = new CartItem();
                c.ProductId = ProductId;
                GetCart.RemoveItem(c);
                _ErrorMessage = "";
            }
            catch
            {
                _ErrorMessage = "Error removing ProductVariant with ProductId:" + ProductId;
            }
        }


        public static void ClearCart()
        {
            GetCart.ClearItems();
        }

        /*
         * <cart total="decimal" totalDisplay="string (currency)">
         * <item>
         * <productId>string</productId>
         * <productName>string</productName>
         * <quantity>int32</quantity>
         * <price>currency string</price>
         * <sum>currency string</sum>
         * <url>string</url>
         * </item>
         * <item>
         * ...
         * </item>
         * </cart>
         */
        public static XPathNodeIterator GetCartXML()
        {
            try
            {
                _ErrorMessage = "";
                return GetCart.ToXml();
            }
            catch (Exception ex) { _ErrorMessage = "Couldt load xmldata!! : " + ex.ToString(); }
            return null;
        }


        public static string FormattedPrice(decimal Price)
        {
            return Price.ToString("c", BusinessLogic.Store.NumberFormatInfo);
        }



        public static string FormattedPrice(string price)
        {
            // Take the input numberformat info
            decimal p = Decimal.Parse(price, BusinessLogic.Store.InputNumberFormatInfo);

            // and output the output numberformatinfo
            return p.ToString("c", BusinessLogic.Store.NumberFormatInfo);
        }

        public static string Newline()
        {
            return System.Environment.NewLine;
        }

        public static string Tabspace()
        {
            return "\t";
        }

        public static string FixedSizeString(string value, int size)
        {
            if (value.Length >= size)
                return value.Substring(0, size - 1);
            int ssize = value.Length;
            for (int i = ssize; i < size; i++)
                value += " ";
            return value;
        }

        public static string FixedSizeStringRight(string value, int size)
        {
            if (value.Length >= size)
                return value.Substring(0, size - 1);
            int ssize = value.Length;
            for (int i = ssize; i < size; i++)
                value = " " + value;
            return value;
        }

        public static void SendOrderConfirmationMail(int OrderId, string To, string From, string Subject)
        {
            SmtpMail.SmtpServer = umbraco.GlobalSettings.SmtpServer;
            MailMessage m = new MailMessage();
            m.From = From;
            m.To = To;
            m.Subject = Subject;
            m.Body = BusinessLogic.Store.GetEmailBody(OrderId);
            SmtpMail.Send(m);
        }

        public static void installsql()
        {
            // install the sql
            string sql = @"CREATE TABLE [dbo].[ecommerceProductVariants]
					(
					[id] [int] NOT NULL IDENTITY(1, 1),
					[NodeId] [int] NOT NULL,
					[ProductId] [nvarchar] (1000) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[Name] [nvarchar] (1000) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[Price] [varchar] (50) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[Deleted] [bit] NOT NULL CONSTRAINT [DF_ecommerceVariants_Deleted] DEFAULT (0),
					[order] [int] NOT NULL
					)

					|

					CREATE TABLE [dbo].[ecommerceOrder]
					(
					[id] [int] NOT NULL IDENTITY(1, 1),
					[customerXML] [ntext] COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[IP] [nvarchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[timestamp] [datetime] NOT NULL CONSTRAINT [DF_eshopOrder_timestamp] DEFAULT (getdate()),
					[paymentMethod] [varchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[status] [varchar] (50) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[sessionId] [varchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL CONSTRAINT [DF_ecommerceOrder_sessionId] DEFAULT (''),
					[total] [nvarchar] (50) COLLATE Danish_Norwegian_CI_AS NOT NULL CONSTRAINT [DF_ecommerceOrder_total] DEFAULT (0),
					[notificationEmail] [nvarchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL CONSTRAINT [DF_ecommerceOrder_notificationEmail] DEFAULT ('')
					)

					|

					CREATE        PROCEDURE [ecommerceGet_Orders_By_Page_And_Status]
					@Status nvarchar (50),
					@CurrentPage int,
					@PageSize int
					AS
					--Create a temp table to hold the current page of data
					--Add and ID column to count the records
					CREATE TABLE #TempTable
					(
					ID int IDENTITY PRIMARY KEY,
					OrderId int,
					Total nvarchar(50),
					[timestamp] datetime,
					)
					--Fill the temporary table with the Customers data
					INSERT INTO #TempTable 
					(
					OrderId,
					Total,
					[timestamp]
					)
					SELECT 
					id,
					total,
					[timestamp]
					FROM 
					ecommerceOrder where status = @Status
					--Create variable to identify the first and last record that should be selected
					DECLARE @FirstRec int, @LastRec int
					SELECT @FirstRec = (@CurrentPage - 1) * @PageSize
					SELECT @LastRec = (@CurrentPage * @PageSize + 1)
					--Select one page of data based on the record numbers above
					SELECT 
					ID,
					OrderId,
					Total,
					[timestamp]
					FROM 
					#TempTable
					WHERE 
					ID > @FirstRec 
					AND
					ID < @LastRec
					ORDER BY ID DESC
					|
					CREATE TABLE [dbo].[ecommerceProduct]
					(
					[NodeId] [int] NOT NULL,
					[useMultipleProductVariants] [bit] NOT NULL CONSTRAINT [DF_ecommerceProduct_useMultipleVariants] DEFAULT (0),
					[Name] [nvarchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL CONSTRAINT [DF_ecommerceProduct_Name] DEFAULT (''),
					[Weight] [int] NOT NULL CONSTRAINT [DF_ecommerceProduct_Weight] DEFAULT (0)
					)
					|
					CREATE TABLE [dbo].[ecommerceOrderlines]
					(
					[id] [int] NOT NULL IDENTITY(1, 1),
					[orderId] [int] NOT NULL,
					[productId] [nvarchar] (500) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[productName] [nvarchar] (50) COLLATE Danish_Norwegian_CI_AS NOT NULL,
					[quantity] [int] NOT NULL,
					[price] [nvarchar] (50) COLLATE Danish_Norwegian_CI_AS NOT NULL
					)
					|
					INSERT INTO [umbracoApp] ([appAlias], [sortOrder], [appIcon], [appName], [appInitWithTreeAlias]) VALUES (N'store', 8, N'store.gif', N'Store', N'')
					|
					INSERT INTO [umbracoAppTree] ([appAlias], [treeAlias], [treeSilent], [treeInitialize], [treeSortOrder], [treeTitle], [treeIconClosed], [treeIconOpen], [treeHandlerAssembly], [treeHandlerType]) VALUES (N'store', N'store', 0, 1, 0, N'Store', N'folder.gif', N'folder_o.gif', N'Umbraco.Ecommerce', N'DataControls.UmbracoExtension')
					";

            string[] sqlstatements = sql.Split('|');

            try
            {
                foreach (string s in sqlstatements)
                {
                    Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(umbraco.GlobalSettings.DbDSN, CommandType.Text, s);
                }
            }
            catch
            {
            }
        }
    }
}
